//
//  Homepage.m
//  YWZY
//
//  Created by zuqiu on 17/2/9.
//  Copyright © 2017年 zuqiu. All rights reserved.
//
#import "VerifyHelper.h"
#import "NSString+Helper.h"
#import "Homepage.h"
#import "HttpRequest.h"
#import "UIHelper.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "AFNetworkingHelper.h"
#import "Registered.h"
#import "MD5Encryption.h"
#import <CommonCrypto/CommonDigest.h>
//#import "mapPage.h"
#import "UpdateVersion.h"
#define APPID @"1257994954"
#define APP_DownloadURL @"itms-services://?action=download-manifest&url=https://www.sunsung.cc:9443/ios/fdhsydwh2017.plist"


@implementation Homepage

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;

}
//- (void)viewDidAppear:(BOOL)animated
//{
//    [UpdateVersion hsUpdateAppStoreAppid:APPID andVC:self];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    [_didReme setImage:[UIImage imageNamed:@"login_checkon"] forState:UIControlStateNormal];
    [_didReme setImage:[UIImage imageNamed:@"login_checkoff"] forState:UIControlStateSelected];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString * c = [userDefaults objectForKey:@"account"];
    NSString * p =[userDefaults objectForKey:@"password"];
    
    if (c.length > 0) {
        _passTxt.text = p;
        _countTxt.text = c;
        _didReme.selected = YES;
    }else{
        _didReme.selected = NO;
    }
    _passTxt.secureTextEntry = YES;
}

#pragma mark UITextField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField ==self.countTxt) {
        [self.passTxt becomeFirstResponder];
    } else {
        [self.passTxt resignFirstResponder];
        [self login:nil];
    }
    return YES;
}

#pragma mark - 登录按钮
- (IBAction)login:(UIButton *)sender {
    if (self.didReme.selected == YES) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:_countTxt.text  forKey:@"account"];
        [userDefaults setObject:_passTxt.text forKey:@"password"];
        [userDefaults synchronize];
    }
    //获取当前设备中应用的版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *serviceVersion =   [userDefaults objectForKey:@"serviceVersion"];
    if (![currentVersion isEqualToString:serviceVersion]) {
        [self updateApp:serviceVersion];
    }else{
            [self loginFunc];
    }


}

- (void)updateApp:(NSString *)updateVersion
{
    //获取当前设备中应用的版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    
    //判断两个版本是否相同
    if (![currentVersion isEqualToString:updateVersion]) {
        NSString *titleStr = [NSString stringWithFormat:@"检查更新：%@", @"黄山外呼"];
        NSString *messageStr = [NSString stringWithFormat:@"发现新版本（%@）,是否更新", updateVersion];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:titleStr message:messageStr delegate:self cancelButtonTitle:@"立即升级" otherButtonTitles:nil, nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            [alert show];
        });
    } else {  //版本号和app store上的一致
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIHelper showTipsWithText:@"当前已是最新版本！" inView:nil];
        });
    }
}


//判断用户点击了哪一个按钮
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) { //点击”升级“按钮，就从打开app store上应用的详情页面
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APP_DownloadURL]];
    }
    
}

#pragma mark - 记住密码按钮
- (IBAction)didReme:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    if (sender.isSelected == YES) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:_countTxt.text  forKey:@"account"];
        [userDefaults setObject:_passTxt.text forKey:@"password"];
        [userDefaults synchronize];
    }else {
   
    }
}



#pragma mark - 成功处理
- (void)successWithTask:(NSURLSessionDataTask *)task response:(NSDictionary *)response {
    //    NSString *str = response[@"resultcode"];
    NSDictionary *userrightlist  = response[@"object"];
    NSString *Service_Token  = userrightlist[@"token"];
    NSString *resultcode = response[@"resultcode"];
    NSString *text = response[@"resultdesc"];
    NSLog(@"%@",text);
    [UIHelper showTipsWithText:text inView:self.view];
    if ([resultcode isEqualToString:@"SUCCESS" ])
    {
                MainWeb *mVc = [MainWeb new];
                mVc.reLastUrl  = [NSString stringWithFormat:@"%@?token=%@",shouYePage,Service_Token];
                [self.navigationController pushViewController:mVc animated:YES];
    }
}

#pragma mark - 返回处理
- (void)failureWithTask:(NSURLSessionDataTask *)task error:(NSError *)error {
    [UIHelper showErrorWithText:@"网络异常，请稍候重试" inView:self.view];
}

- (BOOL)isEmptyString:(NSString *)str{
    return  [VerifyHelper isEmptyString:str];
}

- (void)loginFunc
{
    [self.view endEditing:YES];
    
    NSString *username = [[self.countTxt text] trimString];
    NSString *phoneNub = [self.passTxt text] ;
    
    
    if ([self isEmptyString:username]) {
        [UIHelper showTipsWithText:@"用户名不能为空" inView:self.view];
    }else if([self isEmptyString:phoneNub]){
        [UIHelper showTipsWithText:@"密码不能为空" inView:self.view];
    }else{
        [UIHelper showMessage:@"正在查询..." toView:self.view];
        //        NSString *jiami =[MD5Encryption md5by32:password];
        NSDictionary *params = @{@"account": username, @"passwd": [MD5Encryption md5by32:phoneNub]};
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        // NSLog(@"%@",jsonData);
        NSString *paraStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        //把字典和数组转换成json字符串
        NSDictionary *paraDic = @{@"HTTPJSONKEY":paraStr};
        HJLog(@"%@",LoginURL);
        AFNetworkingHelper *helper = [AFNetworkingHelper defaultHelper];
        [helper sendRequestWithURLString:LoginURL
                              parameters:paraDic
                                 success:^(NSURLSessionDataTask *task, NSDictionary *response) {
                                     [UIHelper dismissLoadingInView:self.view];
                                     [self successWithTask:task response:response];
                                 }
                                 failure:^(NSURLSessionDataTask *task, NSError *error) {
                                     [UIHelper dismissLoadingInView:self.view];
                                     [self failureWithTask:task error:error];
                                 }];
    }
}

#pragma mark - 打电话
-(void)callPhoneMethod:(NSString *)phone{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

#pragma mark - 键盘下落
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
//

@end
